#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime
from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, Float, Boolean, String, Unicode, UnicodeText, \
    DateTime, TIMESTAMP, func, or_
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""Message collection has
    userid:         用户id（int）
    peerid:         对方id（int）
    content:        内容（string）
    mtype:          收或发（int）
    ctime:          创建时间（datetime）
"""

MESSAGE_TYPE_SEND, MESSAGE_TYPE_RECEIVE = range(2)

class MessagePetItem(object):
    """docstring for TopicTitleItem"""

    def to_dict(self):
        res = {}
        res['userid'] = self.userid
        res['peerid'] = self.peerid
        res['content'] = self.content
        res['mtype'] = self.mtype
        res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S")\
            if self.ctime else ""
        return res

    def __repr__(self):
        return "%d" % (self.userid)


message_pet_table = Table(
    'message_pet', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('userid', Integer, nullable=False),
    Column('peerid', Integer, nullable=False),
    Column('content', Unicode(255), nullable=False),
    Column('mtype', Integer, nullable=False),
    Column('ctime', TIMESTAMP, server_default=func.now())
)

mapper(MessagePetItem, message_pet_table)

def create_message_pet_table_if_not_exist():
    metadata.create_all(engine)


def add_message_pet_item(p_item):
    item1 = MessagePetItem()
    item1.userid = p_item['peerid']
    item1.peerid = p_item['userid']
    item1.content = p_item['content']
    item1.mtype = MESSAGE_TYPE_RECEIVE

    try:
        session = Session()
        session.add(item1)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_message_pet_by_userid(p_userid, p_begin, p_limit):
    try:
        session = Session()
        items = session.query(MessagePetItem)\
            .filter(MessagePetItem.userid == p_userid)\
            .order_by(MessagePetItem.ctime.desc()) \
            .offset(p_begin).limit(p_limit).all()
        res_list = [item.to_dict() for item in items]
        return res_list
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


def delete_message_pet_by_userid(p_userid):
    try:
        session = Session()
        session.query(MessagePetItem)\
            .filter(MessagePetItem.userid == p_userid)\
            .delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_message_pet_today_by_userid_mtype(p_userid, p_peerid, p_mtype):
    try:
        session = Session()
        today = datetime.date.today()
        starttime = datetime.datetime(today.year, today.month, today.day, 0, 0)
        # endtime = datetime.datetime.now()
        item_query = session.query(MessagePetItem) \
            .filter(MessagePetItem.ctime > starttime) \
            .filter_by(userid=p_userid, peerid=p_peerid, mtype=p_mtype)
        item = item_query.all()
        if item:
            return True
        return None
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


if __name__ == '__main__':
    create_message_pet_table_if_not_exist()
